package com.android.qos;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;

public class PushService extends Service {

    private static final String LOG_TAG = "PushService";
    
    public static final String BROADCAST_ACTION = "com.android.displayevent";
    private static String testUrl = "";
    private String connStatus = "none";
    private String updateStr = "no";
    private Handler keepHandler = new Handler();
    private Handler uiHandler = new Handler();
    private Intent intent;
    private TimerTask keepDeamon;
    private SimuHtmlReq shr;
    
    Timer t = new Timer();

    public class PushBinder extends Binder {
        PushService getService() {
            return PushService.this;
        }
    }
    @Override
    public IBinder onBind(Intent arg0) {
        
        testUrl = arg0.getExtras().getString("serverUrl");
        
        uiHandler.removeCallbacks(sendUpdatesToUI);
        uiHandler.postDelayed(sendUpdatesToUI, 1000); // 1 second
        //connect to server when binding
        connecToServer();
        
        //Init HTML request
        shr = new SimuHtmlReq(testUrl);
        return mBinder;
    }
    
    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            intent.putExtra("status", getConnStatus());
            intent.putExtra("request", shr.getResult());
            intent.putExtra("update", getUpdate());
            sendBroadcast(intent);
            uiHandler.postDelayed(this, 4*1000); // 4 seconds
        }
    };    
    
    private final IBinder mBinder = new PushBinder();

    @Override
    public void onCreate() {
        intent = new Intent(BROADCAST_ACTION);
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(LOG_TAG, "Received start id " + startId + ": " + intent);
        return START_STICKY;
    }
    
    public String getConnStatus() {
        return connStatus;
    }
    public String getUpdate() {
        return updateStr;
    }
    public void connecToServer() {
        //connect to server
        keepDeamon = new TimerTask() {            
            public void run() {
                keepHandler.post(new Runnable() {
                    public void run() {
                        Log.d(LOG_TAG, "test url");
                        testUrl(); 
                    }
                });
           }};
           
           t.schedule(keepDeamon, 300, 300*1000);

    }

    void testUrl() {
        new Thread(new Runnable() {
            public void run() {
                connUrl(testUrl); 
            }
        }).start();
    }
    
    private String connUrl(String myurl) {
        InputStream is = null;
        int len = 1024;
        Log.d(LOG_TAG, "server URL: "+myurl);
        
        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(30000);
            conn.setConnectTimeout(35000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            
            conn.connect();
            
            int response = conn.getResponseCode();
            Log.d(LOG_TAG, "the response code is: " + response);
            if(response == 200) {
                connStatus = "Success";
            } else {
                connStatus = "Fail";
            }
            
            is = conn.getInputStream();
            
            String contentAsString = readIt(is,len);
            Spanned sp = Html.fromHtml(contentAsString);
            Log.d(LOG_TAG, "the content is: " + sp.toString());
            String[] tmp = sp.toString().split("\n");
            for(int i= 0; i<tmp.length;i++) {
                Log.d(LOG_TAG, "tmp "+i+" : "+tmp[i]);
            }
            //updateStr = tmp[tmp.length-1];
            return contentAsString;
        } catch (Exception ee) {
            Log.d(LOG_TAG, "Exception!! " + ee.toString());
            return null;
        }
    }
    
    public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        StringBuilder sb = new StringBuilder();
        while(reader.read(buffer) > 0) {
            sb.append(buffer);
            Arrays.fill(buffer, 0, len, '\0');
        }
        return sb.toString();
    }
    
    
    public void sendRequest() {
        
        shr.encapTest();
    }
    @Override
    public void onDestroy() {       
        uiHandler.removeCallbacks(sendUpdatesToUI);       
        super.onDestroy();
    }   
}
